﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyAlbum.Model;
using MyAlbum.Services;
using MyAlbum.Data;
using System.Web.Routing;
using MyAlbum.Utility;

namespace PersonalAlbum.Controllers
{
    public class SupportController : ApplicationController
    {
        private IDataService<Support> _supportService;
        private IEntryService _entryService;
        private IBlogService _blogService;
        public SupportController()
            : this(ObjectFactory.GetInstance<IDataService<Support>>(),
                ObjectFactory.GetInstance<IEntryService>(),
                ObjectFactory.GetInstance<IBlogService>())
        { }
        public SupportController(IDataService<Support> supportService,
            IEntryService entryService,
            IBlogService blogService)
        {
            this._supportService = supportService;
            this._entryService = entryService;
            this._blogService = blogService;
        }
        /// <summary>
        /// Ajax request for sending an entry to a friend
        /// </summary>
        /// <param name="friendEmail">The target email</param>
        /// <param name="freeText">Some free text to add to the message</param>
        /// <param name="senderName">The name of the sender</param>
        /// <param name="entryId">The id of the entry to send</param>
        /// <returns>Json response</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        [ValidateCaptcha()]
        public ActionResult SendToFriend(string friendEmail, string freeText, string senderName, string itemId, ItemType itemType)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            if (model.Configuration.ShowSendToFriendBox)
            {
                WebLogger.Trace("send to friend");

                try
                {
                    if (itemType == ItemType.Entry)
                    {
                        var entry = this._entryService.GetItemById(itemId);
                        if (entry != null)
                        {
                            new PostOffice(model.Configuration).SentToFriend(friendEmail, HttpUtility.HtmlEncode(freeText ?? string.Empty), HttpUtility.HtmlEncode(senderName ?? string.Empty), entry, new RequestContext(HttpContext, RouteData));
                        }
                        else
                        {
                            WebLogger.Warning("entry not found for send to friend " + itemId);
                        }
                    }
                    else
                    {
                        var entry = this._blogService.GetPost(itemId);
                        if (entry != null)
                        {
                            new PostOffice(model.Configuration).SentToFriend(friendEmail, HttpUtility.HtmlEncode(freeText ?? string.Empty), HttpUtility.HtmlEncode(senderName ?? string.Empty), entry, new RequestContext(HttpContext, RouteData));
                        }
                        else
                        {
                            WebLogger.Warning("post not found for send to friend " + itemId);
                        }
                    }
                    return Json(new { success = true });
                }
                catch (FormatException fe)
                {
                    WebLogger.LogError(fe, "send to friend");
                    //invalid email
                    return Utils.JavascriptError("");
                }
                catch (Exception e1)
                {
                    WebLogger.LogError(e1, "send to friend");
                    return Utils.JavascriptError("");
                }
            }
            else
            {
                WebLogger.Warning("unauthorized entrance to send to friend action");
                return Utils.JavascriptError("");
            }
        }

        [OutputCache(Duration = 120000, VaryByParam = "none", VaryByCustom = "lang")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Terms()
        {
            return View();
        }
        //  [OutputCache(Duration = 120000, VaryByParam = "none", VaryByCustom = "lang")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("support index");
            IEnumerable<Support> requests = null;
            if (model.User.AllowActions())
            {
                requests = this._supportService.GetItems().OrderBy(s => s.IsActive);
            }
            model.SupportRequests = requests;
            return View(model);
        }

        /// <summary>
        /// Ajax request for new support
        /// </summary>
        /// <param name="support"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        public JsonResult AddSupport([Bind(Include = "Name,Email,Subject,Body", Exclude = "Id", Prefix = "Support")] Support support)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("create support");
            JsonResult result;
            try
            {
                var summary = new ModelStateWrapper(ViewData.ModelState);
                this._supportService.AddItem(support, summary);

                if (!summary.IsValid)
                {
                    result = Utils.JavascriptError(model.Localize("Global.SupportMissingParams"));
                }
                else
                {

                    if (model.Configuration.EmailOnSupport)
                    {
                        try
                        {
                            new PostOffice(model.Configuration).NotifySupport(support);
                        }
                        catch (Exception e1)
                        {
                            WebLogger.LogError(e1, "error sending support email");
                        }
                    }
                    WebLogger.Trace("suppot created");

                    result = Json(new { success = "true" });
                }
            }
            catch (Exception e1)
            {
                if (support != null)
                {
                    WebLogger.LogError(e1, "Error on support. Support details:\r\n from :" + support.Name + ";email:" + support.Email + ";subject:" + support.Subject + ";body:" + support.Body);
                }
                else
                {
                    WebLogger.LogError(e1, "support object is null");
                }
                result = Utils.JavascriptError("");
            }
            return result;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult Update(string supportId)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("update support");

            try
            {
                var item = this._supportService.GetItems().FirstOrDefault(s => s.Id == supportId);
                if (item != null)
                {
                    item.IsActive = false;
                    this._supportService.UpdateItem(item, new ModelStateWrapper(ModelState));
                    WebLogger.Trace("support updated");

                }
                else
                {
                    WebLogger.Warning("support not found for update " + supportId);
                }
                return RedirectToAction("Index");

                //TempData["message"] = this._lang.GetText("Global.SupportUpdated");
            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1, "error updating support");
                model.ErrorMessage = model.Localize("Global.Error");
                return View("Index");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        // [ValidateAn tiForgeryToken()]
        [Authorize(Roles = RolesManager.AdminRoles)]
        public ActionResult Delete(string supportId)
        {
            var model = (PersonalAlbumModel)ViewData.Model;
            WebLogger.Trace("delete support");
            try
            {
                var item = this._supportService.GetItems().FirstOrDefault(s => s.Id == supportId);
                if (item != null)
                {
                    this._supportService.DeleteItem(item);
                    WebLogger.Trace("support deleted");
                }
                else
                {
                    WebLogger.Warning("support not found for delete " + supportId);
                }
                return RedirectToAction("Index");
                //TempData["message"] =this._lang.GetText("Global.SupportDeleted");

            }
            catch (Exception e1)
            {
                WebLogger.LogError(e1);
                model.ErrorMessage = model.Localize("Global.Error");
                return View("Index");
            }
        }
    }
}
